package com.smalljj.comm;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Application;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

//定时器定位类
public class LocationApplicationBean extends Application {
	
	//定位时间间隔(秒)
	private static int myTime = 12;
	
	//是否启动了定位API
	private boolean isOpenLocation = false;
	
	//是否启动了定位线程
	private boolean isOpenLocationTask = false;
		
	private LocationClientOption option = null;
	
	private LocationClient mLocationClient = null; //定位类
	
	private BDLocationListener mListenner = new MyLocationListenner ();
	
	private DBHelper dbHelper = null;

	//定时器
	private Timer myLocationTimer = null;
	
	//定时线程
	private TimerTask myLocationTimerTask = null;
	
	@Override
	public void onCreate() {
		mLocationClient = new LocationClient(this);
		mLocationClient.registerLocationListener(mListenner);
		Log.i(Constants.LOG_TAG, "创建/打开数据库..." );
		dbHelper = new DBHelper(this);
		Log.i(Constants.LOG_TAG, "成功/打开创建数据库!");
	}

	//接受定位得到的消息
	private class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null){
				return;
			}
			sendBroadcast(location.getLongitude()+"",location.getLatitude()+"");
		}
		@Override
		public void onReceivePoi(BDLocation arg0) {}
	}
	
	//获取到经纬的回调操作
	private void sendBroadcast(String longitude,String latitude) {
		try {
			boolean result = checkPositionChange( longitude,latitude );//是否有改变
			if (result) {//有改变，发的广播
				Intent intent = new Intent();
				intent.setAction("POSITION");
                intent.putExtra("changeflag", "change");//区分标识
                
                //上一个位置
                String[] beforePosition = getBeforePosition();
                intent.putExtra("SP_BF_CREATEDATE", beforePosition[0]);
                intent.putExtra("SP_BF_HOUR", beforePosition[1]);
                intent.putExtra("SP_BF_MINUTE", beforePosition[2] );
                intent.putExtra("SP_BF_LONGITUDE", beforePosition[3]);
                intent.putExtra("SP_BF_LATITUDE", beforePosition[4]);
                intent.putExtra("SP_BF_STAYTIME", beforePosition[5] );
                
				String stayTime = getStayTime();//停留时间
                intent.putExtra("longitude", longitude);//经度
                intent.putExtra("latitude", latitude);//纬度
                intent.putExtra("staytime", stayTime );//停留时间
				sendBroadcast(intent);
				Log.i(Constants.LOG_TAG,"发送有改变位置的广播..." );
			}else{//没有改变，发的广播
				String stayTime = getStayTime();//停留时间
				Intent intent = new Intent();
				intent.setAction("POSITION");
                intent.putExtra("changeflag", "nochange");//区分标识
                intent.putExtra("staytime", stayTime );//停留时间
				sendBroadcast(intent);
				Log.i(Constants.LOG_TAG,"发送无改变位置的广播..." );
			}
		} catch (Exception e) {
			Log.i(Constants.LOG_TAG,"发送广播异常" + e.toString());
		}
	}
	
	/**
	 * start定位
	 */
	public  void startLocation() {
		try {
			if (!isOpenLocation){//如果没有打开
				option = new LocationClientOption();
				option.setOpenGps(true);
				option.setAddrType("all");
				option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
				option.disableCache(true);//禁止启用缓存定位
				//option.setScanSpan( myTime * 1000); //不要设置时间,否则会同时执行两次
				mLocationClient.setLocOption(option);
				mLocationClient.start(); //打开定位
				isOpenLocation = true; //标识为已经打开了定位
			}
		} catch (Exception e) {
			Log.i(Constants.LOG_TAG,"打开定位异常" + e.toString());
		}
	}

	/**
	 * end 定位
	 */
	private void closeLocation() {
		try {
			mLocationClient.stop(); //结束定位
			isOpenLocation = false; //标识为已经结束了定位
		} catch (Exception e) {
			Log.i(Constants.LOG_TAG,"结束定位异常" + e.toString());
		}
	}

	/***
	 * 定时器的回调函数
	 */
	private Handler handler = new Handler() {
		//更新的操作
		@Override
		public void handleMessage(Message msg) {
			getLocationInfo(); //获取经纬度

			Log.i(Constants.LOG_TAG,"调用了获取经纬度方法!");
			super.handleMessage(msg);
		}
	};


	/***
	 * 初始化定时器
	 */
	private void initLocationTime() {
		if (myLocationTimer == null) {
			Log.i(Constants.LOG_TAG,"myLocationTimer 已经被清空了!");
			myLocationTimer = new Timer();
		} else {
			Log.i(Constants.LOG_TAG,"myLocationTimer 已经存在!");
		}
	}

	/***
	 * 初始化 定时器线程
	 */
	private void initLocationTimeTask() {
		myLocationTimerTask = new TimerTask() {
			/***
			 * 定时器线程方法
			 */
			@Override
			public void run() {
				handler.sendEmptyMessage(1); //发送消息
			}
		};
	}

	/***
	 * 初始化 time 对象 和 timetask 对象
	 */
	private void initLocationTimeAndTimeTask() {
		initLocationTime();
		initLocationTimeTask();
	}

	/***
	 * 销毁 time 对象 和 timetask 对象
	 */
	private void destroyLocationTimeAndTimeTask() {
		myLocationTimer = null;
		myLocationTimerTask = null;
	}

	/***
	 * 打开定位定时器线程
	 */
	public void openLocationTask() {
		try {
			if (!isOpenLocationTask){///如果不是打开状态，则打开线程
				startLocation();//启动定位更新经纬度
				//开启定时器
				initLocationTimeAndTimeTask(); //初始化定时器和定时线程
				myLocationTimer.schedule(myLocationTimerTask, myTime * 1000, myTime * 1000);
				Log.i(Constants.LOG_TAG," 打开了定位定时器线程!");
				isOpenLocationTask = true; //标记为打开了定时线程
			} else {
				Log.i(Constants.LOG_TAG," 已经开启了定位定时器线程 !");
			}
		} catch (Exception e) {
			Log.i(Constants.LOG_TAG,"打开定位定时器线程异常:" + e.toString());
		}
	}

	/***
	 * 获取经纬度
	 */
	public void getLocationInfo() {
		/**
		 * 0：正常。
		 * 
		 * 1：SDK还未启动。
		 * 
		 * 2：没有监听函数。
		 * 
		 * 6：请求间隔过短。
		 */
		int i = mLocationClient.requestLocation();
		String TAGfont = "获取经纬度工作状态: ";
		switch (i) {
		case 0:
			Log.i(Constants.LOG_TAG,TAGfont + "正常。");
			break;
		case 1:
			Log.i(Constants.LOG_TAG,TAGfont + "SDK还未启动。");
			break;
		case 2:
			Log.i(Constants.LOG_TAG,TAGfont + "没有监听函数。 ");
			break;
		case 6:
			Log.i(Constants.LOG_TAG,TAGfont + "请求间隔过短。 ");
			break;
		default:
			Log.i(Constants.LOG_TAG,TAGfont + "其他原因	");
		}
	}

	/***
	 * 关闭定位定时器线程
	 */
	public void closeLocationTask() {
		try {
			if (isOpenLocationTask){ //如果是打开状态，则关闭
				closeLocation();
				//关闭定时器
				myLocationTimer.cancel();
				destroyLocationTimeAndTimeTask();
				Log.i(Constants.LOG_TAG," 关闭了定位定时器线程 ");
				isOpenLocationTask = false; //标记为关闭了定时线程
			} else {
				Log.i(Constants.LOG_TAG," 已经关闭了定位定时器线程 ");
			}
		} catch (Exception e) {
			Log.i(Constants.LOG_TAG,"关闭定位定时器线程异常: " + e.toString());
		}
	}

	/***
	 * 检查坐标是否改变
	 * 
	 * @return
	 */
	private boolean checkPositionChange(String longitude,String latitude) {
		try {
			//获取活动的 preferences 对象
			SharedPreferences positionSP = getApplicationContext().getSharedPreferences(Constants.SharedPreferencesName, Activity.MODE_PRIVATE);
			String SP_LONGITUDE = positionSP.getString("SP_LONGITUDE","0");//存储中的经度
			String SP_LATITUDE = positionSP.getString("SP_LATITUDE","0");//存储中的纬度
			String SP_CREATEDATE = positionSP.getString("SP_CREATEDATE","0");//存储中的日期
			String today = Util.getCurrentFormatStr("yyyyMMdd");//今天
			Float staytime = positionSP.getFloat("SP_STAYTIME", 0)+ myTime/60;
			
			Editor SPEditor = positionSP.edit();
			if(SP_LONGITUDE.equals(longitude) 
					&& SP_LATITUDE.equals(latitude)&& SP_CREATEDATE.equals(today)){//坐标没变化
				Log.i(Constants.LOG_TAG,"经纬度没有发生变化!");
				SPEditor.putFloat("SP_STAYTIME", staytime );//停留分钟计
				SPEditor.commit();
				return false;
			}else{//坐标改变了
				Log.i(Constants.LOG_TAG,"经纬度发生变化了!");
				SPEditor.putString("SP_BF_CREATEDATE", positionSP.getString("SP_CREATEDATE","0") );//日
				SPEditor.putString("SP_BF_HOUR", positionSP.getString("SP_HOUR","0") );//时
				SPEditor.putString("SP_BF_MINUTE", positionSP.getString("SP_MINUTE","0") );//分
				SPEditor.putString("SP_BF_LONGITUDE", SP_LONGITUDE );//经度
				SPEditor.putString("SP_BF_LATITUDE", SP_LATITUDE ); //纬度
				SPEditor.putFloat("SP_BF_STAYTIME", staytime ); //停留时间
				
				if((!SP_LONGITUDE.equals("0")) && (!SP_LATITUDE.equals("0"))){
					ContentValues values = new ContentValues();
	                values.put("createdate", positionSP.getString("SP_CREATEDATE","0"));
	                values.put("hour", positionSP.getString("SP_HOUR","0"));
	                values.put("minute", positionSP.getString("SP_MINUTE","0"));
	                values.put("longitude", SP_LONGITUDE );
	                values.put("latitude", SP_LATITUDE );
	                values.put("staytime", staytime );
	                dbHelper.insert(values);//上个坐标写进表
				}
                
				SPEditor.putString("SP_CREATEDATE", today );//日
				SPEditor.putString("SP_HOUR", Util.getCurrentFormatStr("HH") );//时
				SPEditor.putString("SP_MINUTE", Util.getCurrentFormatStr("mm") );//分
				SPEditor.putString("SP_LONGITUDE", longitude );//经度
				SPEditor.putString("SP_LATITUDE", latitude ); //纬度
				SPEditor.putFloat("SP_STAYTIME", 0 );//停留分钟算
				return true;
			}
		} catch (Exception e) {
			Log.i(Constants.LOG_TAG,"保存经纬度，到本地失败!" + e.toString());
			return false;
		}
	}

	/***
	 * 获取停留时间
	 * 
	 * @return
	 */
	public String getStayTime() {
		String staytime = "0";
		try {
			//获取活动的 preferences 对象
			SharedPreferences positionSP = getApplicationContext().getSharedPreferences(Constants.SharedPreferencesName, Activity.MODE_PRIVATE);
			staytime = positionSP.getFloat("SP_STAYTIME", 0)+ "" ; //停留时间
		} catch (Exception e) {
			staytime = "0";
			Log.i(Constants.LOG_TAG,"读取本地存储异常:" + e.toString());
		}
		return staytime;
	}
	
	/***
	 * 获取停留时间
	 * 
	 * @return
	 */
	public String[] getBeforePosition() {
		String[] beforePosition = new String[]{"0","0","0","0","0","0"};
		try {
			//获取活动的 preferences 对象
			SharedPreferences positionSP = getApplicationContext().getSharedPreferences(Constants.SharedPreferencesName, Activity.MODE_PRIVATE);
			beforePosition[0] = positionSP.getString("SP_BF_CREATEDATE","0");
			beforePosition[1] = positionSP.getString("SP_BF_HOUR","0");
			beforePosition[2] = positionSP.getString("SP_BF_MINUTE","0");
			beforePosition[3] = positionSP.getString("SP_BF_LONGITUDE","0");
			beforePosition[4] = positionSP.getString("SP_BF_LATITUDE","0");
			beforePosition[5] = positionSP.getFloat("SP_BF_STAYTIME", 0)+ "" ;
		} catch (Exception e) {
			beforePosition = new String[]{"0","0","0","0","0","0"};
			Log.i(Constants.LOG_TAG,"读取本地存储异常:" + e.toString());
		}
		return beforePosition;
	}
	
}